<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="btnStar">开始</button>
    <button id="btnStop" disabled>暂停</button>
    <div>
      <h1 id="random_name"></h1>
    </div>
    <script>
      var randomName = document.getElementById("random_name");
      var btnStar = document.getElementById("btnStar");
      var btnStop = document.getElementById("btnStop");
      var res = window.localStorage.getItem("result");
      if (res) {
        document.body.removeChild(btnStar);
        document.body.removeChild(btnStop);
        randomName.innerHTML = res;
      }
      // 获取20个姓名
      function setUserName(arr) {
        for (var i = 400; i < 601; i++) {
          arr.push(i);
        }
        return arr;
      }
      // 随机获取0-20之间的整数
      function getRandomIndex(min, max) {
        return Math.floor((max - min) * Math.random());
      }

      var arr = [];
      var result = setUserName(arr);
      //   点击开始 开启定时器 随机渲染姓名
      btnStar.onclick = function () {
        btnStar.disabled = true;
        btnStop.disabled = false;
        var timer = setInterval(() => {
          res = result[getRandomIndex(0, 200)];
          randomName.innerHTML = res;
        }, 20);
        // 点击暂停停止定时器
        btnStop.onclick = function () {
          btnStar.disabled = false;
          btnStop.disabled = true;
          document.body.removeChild(btnStar);
          document.body.removeChild(btnStop);
          window.localStorage.setItem("result", res);
          clearInterval(timer);
        };
      };
    </script>
  </body>
</html>
